package com.xunce.xcworkservice.jwt;

import com.xunce.xcworkservice.exception.CustomException;
import com.xunce.xcworkservice.response.ECode;

import java.security.MessageDigest;
import java.util.UUID;


public class TokenGenerator {

    public static String generateValue() throws CustomException {
        return generateValue(UUID.randomUUID().toString());
    }

    private static final char[] HEX_CODE = "0123456789abcdef".toCharArray();

    //token有效期
    public static final long EXPIRE = 60 * 24 * 365;

    //token头部字段
    public static final String HEADER = "Authorization";

    public static String toHexString(byte[] data) {
        if(data == null) {
            return null;
        }
        StringBuilder r = new StringBuilder(data.length*2);
        for ( byte b : data) {
            r.append(HEX_CODE[(b >> 4) & 0xF]);
            r.append(HEX_CODE[(b & 0xF)]);
        }
        return r.toString();
    }

    public static String generateValue(String param) throws CustomException {
        try {
            String tokenString = UUID.randomUUID().toString() + param;
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(tokenString.getBytes());
            byte[] messageDigest = algorithm.digest();
            return toHexString(messageDigest);
        } catch (Exception e) {
            throw new CustomException("生成Token失败", ECode.TOKEN_CREATE_FAIL);
        }
    }
}
